<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Chat Example</title>
    <link rel="icon" href="favicon.ico" type="image/x-icon" />
    <!-- CSS only -->
    <link href="bootstrap.css" rel="stylesheet" />
    <style>
      html,
      body {
        width: 100%;
        height: 100%;
      }

      #log {
        width: 100%;
        height: 100%;
        overflow: auto;
      }

      .container-fluid {
        height: 100%;
      }
    </style>
  </head>
  <body>
    <div class="container-fluid d-flex flex-column py-2">
      <div class="row">
        <div class="col">
          <p class="text-primary" id="message"></p>
        </div>
      </div>
      <div class="row flex-grow-1">
        <div class="col d-flex">
          <div class="card flex-grow-1">
            <div class="card-body d-flex flex-column">
              <div class="row flex-grow-1 mb-2">
                <div class="col">
                  <div
                    id="log"
                    class="bg-light text-dark"
                    style="max-height: 800px; overflow-y: scroll"
                  ></div>
                </div>
              </div>
              <div class="row">
                <div class="col">
                  <form class="row" id="form">
                    <div class="col-10">
                      <input
                        type="text"
                        class="form-control"
                        id="msg"
                        placeholder="普通消息（仅支持ping）"
                      />
                    </div>
                    <div class="col-1">
                      <input
                        type="submit"
                        class="btn btn-primary"
                        value="发送"
                      />
                    </div>
                    <div class="col-1">
                      <input
                        type="button"
                        id="clear"
                        class="btn btn-danger"
                        value="清屏"
                      />
                    </div>
                  </form>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="col d-flex">
          <div class="card flex-grow-1">
            <div class="card-header">房间操作区</div>
            <div class="card-body">
              <div class="input-group mb-3">
                <input
                  type="text"
                  class="form-control"
                  id="room"
                  placeholder="房间标识符"
                />
                <button
                  class="btn btn-outline-secondary"
                  type="button"
                  id="join_room"
                >
                  加入房间
                </button>
                <button
                  class="btn btn-outline-secondary"
                  type="button"
                  id="leave_room"
                >
                  离开房间
                </button>
              </div>
              <div class="input-group mb-3">
                <input
                  type="text"
                  class="form-control"
                  id="register"
                  placeholder="用户标识符"
                />
                <button
                  class="btn btn-outline-secondary"
                  type="button"
                  id="register_id"
                >
                  注册用户
                </button>
              </div>
              <div class="input-group mb-3">
                <input
                  type="text"
                  class="form-control"
                  id="broadcast"
                  placeholder="广播消息"
                />
                <button
                  class="btn btn-outline-secondary"
                  type="button"
                  id="send_broadcast"
                >
                  发送广播
                </button>
              </div>
              <div class="input-group mb-3">
                <span class="input-group-text">目标：</span>
                <input type="text" class="form-control" id="to_target" />
                <span class="input-group-text">目标类型：</span>
                <select class="form-select" id="target_type">
                  <option selected value="room">房间</option>
                  <option value="personal">个人</option>
                  <option value="group">用户组</option>
                </select>
                <span class="input-group-text">消息内容：</span>
                <input type="text" class="form-control" id="content_target" />
                <button
                  class="btn btn-outline-primary"
                  type="button"
                  id="send_to_target"
                >
                  ws发送
                </button>
                <button
                  class="btn btn-outline-secondary"
                  type="button"
                  id="api_send"
                >
                  xhr发送
                </button>
              </div>
              <div class="input-group mb-3">
                <button class="btn btn-danger" type="button" id="w1_pressure">
                  反复注册2下
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="row my-2">
        <div class="col-11">
          <div class="input-group mb-3">
            <input
              type="text"
              class="form-control"
              id="user_id"
              value="user_id"
              placeholder="用户标识符"
            />
            <input
              type="text"
              class="form-control"
              id="attach"
              value="attach"
              placeholder="附加数据"
            />
            <button
              class="btn btn-outline-secondary"
              type="button"
              id="connect"
            >
              建立连接
            </button>
          </div>
        </div>
        <div class="col-1">
          <button class="btn btn-danger" id="close">断开连接</button>
        </div>
      </div>
    </div>

    <script src="index.browser.js"></script>
    <script type="text/javascript">
      function getQueryString(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return decodeURI(r[2]);
        return null;
      }

      //创建ajax函数
      function ajax(options) {
        options = options || {};
        options.type = (options.type || "GET").toUpperCase();
        options.dataType = options.dataType || "json";
        params = formatParams(options.data, options.dataType);

        //创建-第一步
        var xhr;
        //非IE6
        if (window.XMLHttpRequest) {
          xhr = new XMLHttpRequest();
        } else {
          //ie6及其以下版本浏览器
          xhr = ActiveXObject("Microsoft.XMLHTTP");
        }

        //接收-第三步
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4) {
            let status = xhr.status;
            if (status >= 200 && status < 300) {
              options.success &&
                options.success(xhr.responseText, xhr.responseXML);
            } else {
              options.error && options.error(status);
            }
          }
        };

        //连接和发送-第二步
        if (options.type === "GET") {
          xhr.open("GET", options.url + "?" + params, true);
          xhr.send(null);
        } else if (options.type === "POST") {
          xhr.open("POST", options.url, true);
          //设置表单提交时的内容类型
          if (options.dataType === "json") {
            xhr.setRequestHeader("Content-Type", "application/json");
          } else {
            xhr.setRequestHeader(
              "Content-Type",
              "application/x-www-form-urlencoded"
            );
          }

          xhr.send(params);
        }
      }

      //格式化参数
      function formatParams(data, dataType) {
        if (dataType === "json") {
          return JSON.stringify(data);
        } else {
          let arr = [];
          for (let name in data) {
            arr.push(
              encodeURIComponent(name) + "=" + encodeURIComponent(data[name])
            );
          }
          arr.push(("v=" + Math.random()).replace(".", ""));
          return arr.join("&");
        }
      }

      window.onload = function () {
        console.log("onload");
        var msg = document.getElementById("msg");
        var conn = null;
        var log = document.getElementById("log");

        function appendLog(item) {
          var doScroll =
            log.scrollTop > log.scrollHeight - log.clientHeight - 1;
          log.appendChild(item);
          if (doScroll) {
            log.scrollTop = log.scrollHeight - log.clientHeight;
          }
        }

        function clearLog() {
          log.innerHTML = "";
          document.getElementById("message").innerText = "";
        }

        // 连接websocket服务器
        function connect(uid, attach) {
          if (conn) {
            return;
          }
          if (window["WebSocket"]) {
            let schema = "ws";
            if (getQueryString("wss")) {
              schema = "wss";
            }

            const conOptions = {
              // url: `${schema}://${document.location.host}?uid=${uid}&attach=${attach}`,
              url: `${schema}://127.0.0.1:8082?uid=${uid}&attach=${attach}`,
              close: function (evt) {
                var item = document.createElement("div");
                item.innerHTML =
                  "<i class='text-warning'>Connection closed.</i>";
                appendLog(item);
              },
              message: function (evt, data) {
                console.log('got message: ', data, 'original: ', evt.data)
                const item = document.createElement("div");
                item.innerText = data;
                appendLog(item);
              },
            };

            conn = Wmc(conOptions);
          } else {
            var item = document.createElement("div");
            item.innerHTML = "<b>Your browser does not support WebSockets.</b>";
            appendLog(item);
          }
        }

        document.getElementById("form").onsubmit = function () {
          console.log("form submit");
          if (!conn) {
            return false;
          }
          if (!msg.value) {
            return false;
          }
          conn.sendRaw(msg.value);
          return false;
        };

        document.getElementById("close").addEventListener("click", function () {
          console.log("close");
          if (!conn) {
            return;
          }
          conn.close();
          conn = null;
        });
        document
          .getElementById("join_room")
          .addEventListener("click", function () {
            console.log("join_room");
            if (!conn) {
              console.warn("no conn");
              return;
            }
            let roomId = document.getElementById("room").value;
            conn.join(roomId);
          });
        document
          .getElementById("leave_room")
          .addEventListener("click", function () {
            console.log("leave_room");
            if (!conn) {
              return;
            }
            let roomId = document.getElementById("room").value;
            conn.leave(roomId);
          });

        document
          .getElementById("register_id")
          .addEventListener("click", function () {
            console.log("register_id");
            if (!conn) {
              return;
            }
            let userId = document.getElementById("register").value;
            conn.register(userId);
          });

        document
          .getElementById("send_broadcast")
          .addEventListener("click", function () {
            console.log("send_broadcast");
            if (!conn) {
              return;
            }
            let message = document.getElementById("broadcast").value;
            conn.broadcast(message);
          });

        document
          .getElementById("api_send")
          .addEventListener("click", function () {
            console.log("api_send");
            let to = document.getElementById("to_target").value;
            let type = document.getElementById("target_type").value;
            let content = document.getElementById("content_target").value;

            ajax({
              url: "/push",
              type: "POST",
              dataType: "json",
              data: {
                to: to,
                type: type,
                content: content,
              },
              success: function (response, xml) {
                document.getElementById("message").innerText = JSON.stringify(
                  response
                );
              },
              error: function (status) {
                document.getElementById("message").innerText = JSON.stringify(
                  status
                );
              },
            });
          });

        document
          .getElementById("send_to_target")
          .addEventListener("click", function () {
            console.log("send_to_target");
            if (!conn) {
              return;
            }
            let to = document.getElementById("to_target").value;
            let type = document.getElementById("target_type").value;
            let content = document.getElementById("content_target").value;
            conn.send(to, type, content);
          });

        document
          .getElementById("connect")
          .addEventListener("click", function () {
            console.log("connect");
            let uid = document.getElementById("user_id").value;
            let attach = document.getElementById("attach").value;
            connect(uid, attach);
          });

        document.getElementById("clear").addEventListener("click", function () {
          clearLog();
        });

        document
          .getElementById("w1_pressure")
          .addEventListener("click", function () {
            const max = 2;
            let i = 0;
            let schema = "ws";
            if (getQueryString("wss")) {
              schema = "wss";
            }
            let conn = null;
            while (i < max) {
              conn = new WebSocket(
                // schema + "://" + document.location.host + "?uid=1"
                schema + "://" + "127.0.0.1:8082/" + "?uid=1"
              );
              conn.onclose = function (evt) {
                var item = document.createElement("div");
                item.innerHTML =
                  "<i class='text-warning'>Connection closed.</i>";
                appendLog(item);
              };
              conn.onmessage = function (evt) {
                var messages = evt.data.split("\n");
                for (var i = 0; i < messages.length; i++) {
                  var item = document.createElement("div");
                  item.innerText = messages[i];
                  appendLog(item);
                }
              };
              i++;
            }
          });
      };
    </script>
  </body>
</html>
